#! /usr/bin/python2.4

# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Routines for creating standard local test repositories"""

import os
import sys

import gvn.util
from gvn import platform
from gvn import svncmd

import svn.repos
from svn.core import SubversionException, svn_path_internal_style


def CreateEmptyRepository(dir):
  """Create an empty subversion repository in the 'dir' directory.

  A dummy pre-revprop-change hook that returns success for any test will be
  installed in the empty repository.

  Arguments:
    dir -- The directory in which to create the empty repository.  It must
           already have been created.

  Returns:
    A tuple of the path to the newly created repository and the repository
    object itself, or a tuple with None as the path if repository creation
    failed.

  """

  repo = svn.repos.create(dir,
                          None, None, # unused
                          None,       # No client configuration
                          None,       # No filesystem configuration
                          None)       # No pool

  if sys.platform == 'win32':
    # Windows has no symlinks (nor /bin/true, for that matter), so we'll
    # create a tiny .bat file to serve in its stead.
    f = open(os.path.join(dir, 'hooks/pre-revprop-change.bat'), 'w')
    f.write('EXIT /B 0\n')
    f.close()
  else:
    f = open(os.path.join(dir, 'hooks/pre-revprop-change'), 'w')
    f.write('#!/bin/sh\ntrue\n')
    f.close()
    os.chmod(os.path.join(dir, 'hooks/pre-revprop-change'), 0755)

  return (dir, repo)


def CreateRepository(dir, testdump=None):
  """Create a "standard" subversion repository, loading the given dumpfile.

  Arguments:
    dir      -- the directory in which to create the test repository
    testdump -- the file from which to load the repository contents; if no
                dumpfile is specified, the file in testdata/dumpfile is used

  Returns:
    The absolute path to the repository (with / instead of \\, if we're on
    Windows), or None if creation and/or population failed.

  """

  if not testdump:
    testdump = 'testdata/dumpfile'

  (repo_dir, repo) = CreateEmptyRepository(dir)
  if not repo or not repo_dir or repo_dir != dir:
    return None

  f = open(testdump, 'r')
  # try...except...finally doesn't work until Python 2.5.
  try:
    try:
      tmp_pool = svn.core.Pool()
      svn.repos.load_fs2(repo, f,
                         None,                       # No feedback stream
                         svn.repos.load_uuid_ignore,
                         None,                       # No parent dir
                         False, False,               # No commit hooks
                         None,                       # No cancel function
                         tmp_pool)
    except SubversionException, e:
      # Win32 error 1224, "The requested operation cannot be performed on a
      # file with a user-mapped section open."
      if (sys.platform == 'win32' and
          gvn.util.APR_TO_OS_ERROR(e.apr_err) == 1224):
        sys.stderr.write("""\
If this call fails on your Windows machine, you may need to disable any
realtime virus scanner you have running (at least in your Temp directory,
'C:\\Documents and Settings\\<user>\\Local Settings\\Temp\\').
""")
      raise
  finally:
    f.close()
    tmp_pool.destroy()

  return svn_path_internal_style(repo_dir)

if __name__ == '__main__':
  if len(sys.argv) != 2:
    sys.stderr.write('need 1 (and only 1) path to the repository\n')
    sys.exit(2)
  path = sys.argv[1]
  CreateRepository(path)
  svncmd.RunSvn(['ls', '-Rv', "file:///%s" % (os.path.abspath(path),)])
